<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Register extends CI_Controller {

	public function __construct(){
    	parent::__construct();
		if(!isset($_SESSION)): session_start(); endif;
		$this->load->model('users_model');
		$this->load->helper('product_helper');
		// load paypal library
		$this->load->library('paypal_lib');
    }

	public function index($type=''){
		if(!in_array($type,array('free','premium','reseller'))){
			$data['title']= "Select your account";
			$data['main_content'] = 'signup_select_view';
			return $this->load->view('common/temp', $data);
		}
		$action = 0;
		$post_data = array();
		$post_data = $_POST;
		$data['post_data'] = $post_data;
		$data['title']= "Sign Up My Life My Eulogy";
		$data['main_content'] = 'register_view';
		$data['type'] = $type;
		// Get default MLME product details
		if($type=='premium'){
			$this->db->where('type','default');
			$this->db->where('enable',1);
			$product = $this->db->get('mlme_products')->result();
			$data['product_details'] = $product[0];
		}
		if($type=='reseller'){
			$this->db->where('type','package');
			$this->db->where('enable',1);
			$product = $this->db->get('mlme_products')->result();
			$data['product_details'] = $product[0];
		}
		$action = $this->input->post('action');//register submit
		if($action == 1){
			return $this->save();
		}
		$this->load->view('common/temp', $data);
	}

	// Save the user data
	function save(){
		//dont forget to secure
		$usertype = strtolower($this->input->post('type'));
		$save = $this->users_model->create_users();
		if($save['insert']){
			switch($usertype){
				default:
				case 'free':
					$this->_free($save);
					break;
				case 'reseller':
				case 'premium':
					$this->_premium($save,$usertype);
					break;

			}//endswitch
		} else {
			$this->message->set('error', 'Failed to save registration. Please contact administrator.');
		}
		$data['usertype'] = $usertype;
		$data['main_content'] = 'register_step2_view';
		$this->load->view('common/temp', $data);
	}

	//register save free
	function _free($save){
		$send_to = $this->input->post('reg-email');
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$headers .= "From: My Life My Eulogy <lalene@advanzweb.com> \r\n";
		$subject = "My Life My Eulogy - Verify Account";
		$body  = 'Your registration on mylifemyeulogy.com is almost complete.  <br/> Please click the link below to verify your account.  <br/>If the link is not clickable, please copy and paste in to the URL bar of your browser.  <br/>Thank you.<br/>';
		$url = base_url()."register/verify-account/".$save['userid'];
		$body .= "<a href=".$url.">$url</a>";
		if(mail($send_to, $subject, $body,$headers)){
			$this->message->set('success', 'Your registration is almost done, check your email to verify your account. Make sure to check your Spam folder just in case our verification email was filtered as Spam.');
		} else {
			$this->message->set('error', 'Error sending email.');
		}
		return true;
	}

	//premuim save register
	function _premium($save,$usertype){
		$transacData = array();
		$transacData['userid'] = $save['real_userid'];
		$transacData['productid'] = $this->input->post('prodid');
		$transacData['package_code_entered'] = $this->input->post('package_code_entered','');

		$stamp = strtotime("now");
		$ip = Product_helper::getIP();
		$ordernum = 'T'.($stamp-@$ip);
		$ordernum = str_replace(".", "", $ordernum);
		$transacData['order_number'] = $ordernum;

		//get total from selected products
		//in this case only one product later we will have array and total of it
		$price = Product_helper::get($this->input->post('prodid'), 'price');
		$price = $price->price;
		$order_total = $price;

		//if user has entered package code
		if( strlen($package_code = $this->input->post('package_code')) ){
			//we need to verify if package code is valid, if valid, we will make the amount 0 else amount is the vip price.
			if($this->is_packagecode_valid($package_code)){
				$order_total = 0;
			}
		}

		$product_name = Product_helper::get($this->input->post('prodid'), 'name');
		$transacData['order_total'] = $order_total;
		$transacData['order_currency'] = $this->config->item('currency');
		$transacData['order_status'] = 'pending'; //not payed, by default
		$transacData['date_created'] = date('y-m-d h:m:s');
		$transacData['date_modified'] = date('y-m-d h:m:s');
		$transacData['modifiedby'] = $save['real_userid'];;
		$transacData['ip_address'] = $ip;
		$transacData['productid'] = $this->input->post('prodid');	//for now only one
		$transacData['qty'] = 1;  //for now only one
		$transacData['item_price'] = $price;  //for now same
		$transacData['order_type'] = 'vip';

		//Save transaction
		if($this->db->insert('mlme_orders', $transacData)){
			$data['transac_details'] = $transacData;
			//if total > 0 proceed to checkout
			if($order_total > 0){
				//to be sent to paypal post
				$custom = null;
				$custom->userid = $transacData['userid'];
				$custom->user_email = $_SESSION['email'];
				$custom = json_encode($custom);

				$this->setPaypalForm($product_name->name,$transacData['productid'],$transacData['item_price'], $custom);
				$data['paypal_form'] = $this->paypal_lib->paypal_form();
			}
			if($usertype=='premium'){
				if($order_total > 0){
					$this->message->set('success', 'Your account has been created. Please secure your payment to be a PREMIUM account holder and enjoy the premium features of My Life My Eulogy Website.');
				}else{
					$this->message->set('success', 'Your account has been created. Welcome and enjoy the premium features of My Life My Eulogy Website.');
				}
			}else {
				$this->message->set('success', 'Your account has been created. Please secure your payment to BUSINESS with us.');
			}
		} else {
			$data['transac_details'] = null;
			$this->message->set('warning', 'Your account has been created but the transaction was failed to save. Please contact administrator.');
		}
		return true;
	}

	public function captcha_validate(){

	  $this->load->helper("captcha");
	  print_r(my_sessions());

	}

	function email_exist(){
		//$this->load->model('users_model');

		$check = $this->users_model->check_email();
		echo ($check)? 'true':'false';

	}

	function verify_account($encrypted_id){
		$verify = $this->users_model->verify_account($encrypted_id);
		$con_msg = (isset($_SESSION['sess_con_msg']))? $_SESSION['sess_con_msg']:'';
		if($verify && !empty($con_msg)){
			$_SESSION['is_logged_in'] = true;
			redirect('profile');
		}else{
			redirect('login');
		}//end if
	}

	//Set paypalform fields
	function setPaypalForm($item_name='', $item_number='', $amount='', $custom=''){
//		echo '<br>na';
//		echo $item_name;
//		echo '<br>num';
//		echo $item_number;
//		echo '<br>a';
//		echo $amount;
//		echo '<br>';exit;
		$business = 'lalene_1328513880_biz@advanzweb.com';
//		$item_name = 'Paypal Test Transaction';
//		$item_number = '1234';
//		$amount = '197';
		//$this->paypal_lib->add_field('business', $this->config->item('merchant_paypal'));
		$this->paypal_lib->add_field('business', $business);
	    $this->paypal_lib->add_field('return', site_url('register/paypal/success'));
	    $this->paypal_lib->add_field('cancel_return', site_url('register/paypal/cancel'));
	    $this->paypal_lib->add_field('notify_url', site_url('register/paypal/ipn')); // <-- IPN url

	    //set session true
	    $this->paypal_lib->add_field('custom', $custom); // <-- Verify return

	    $this->paypal_lib->add_field('item_name', $item_name);
	    $this->paypal_lib->add_field('item_number', $item_number);
	    $this->paypal_lib->add_field('amount', $amount);

		// if you want an image button use this:
		$this->paypal_lib->image('reg-paypal-btn.png');

		// otherwise, don't write anything or (if you want to
		// change the default button text), write this:
		// $this->paypal_lib->button('Click to Pay!');
		return true;
	}

	/**
	 * Paypal method used to call this function when calling about paypal
	 */
	 function paypal($task){
	 	switch($task){
	 		case 'success':
	 			$this->_success();
	 			break;
	 		case 'cancel':
	 			$this->_cancel();
	 			break;
	 		case 'ipn':
	 			$this->_ipn();
	 			break;

	 	}
	 }

	function _cancel(){
		$this->load->view('paypal/cancel');
	}

	function _success(){
		// This is where you would probably want to thank the user for their order
		// or what have you.  The order information at this point is in POST
		// variables.  However, you don't want to "process" the order until you
		// get validation from the IPN.  That's where you would have the code to
		// email an admin, update the database with payment status, activate a
		// membership, etc.

		// You could also simply re-direct them to another page, or your own
		// order status page which presents the user with the status of their
		// order based on a database (which can be modified with the IPN code
		// below).

		$data['pp_info'] = $this->input->post();
		$this->load->view('paypal/success', $data);
	}

	 function _ipn(){
		// Payment has been received and IPN is verified.  This is where you
		// update your database to activate or process the order, or setup
		// the database with the user's order details, email an administrator,
		// etc. You can access a slew of information via the ipn_data() array.

		// Check the paypal documentation for specifics on what information
		// is available in the IPN POST variables.  Basically, all the POST vars
		// which paypal sends, which we send back for validation, are now stored
		// in the ipn_data() array.

		// For this example, we'll just email ourselves ALL the data.
		$to    = 'lalene@advanzweb.com';    //  your email

		if ($this->paypal_lib->validate_ipn())
		{
			$body  = 'An instant payment notification was successfully received from ';
			$body .= $this->paypal_lib->ipn_data['payer_email'] . ' on '.date('m/d/Y') . ' at ' . date('g:i A') . "\n\n";
			$body .= " Details:\n";

			foreach ($this->paypal_lib->ipn_data as $key=>$value)
				$body .= "\n$key: $value";

			// load email lib and email results
			$this->load->library('email');
			$this->email->to($to);
			$this->email->from($this->paypal_lib->ipn_data['payer_email'], $this->paypal_lib->ipn_data['payer_name']);
			$this->email->subject('CI paypal_lib IPN (Received Payment)');
			$this->email->message($body);
			$this->email->send();
		}
	}//endif

	//check if package code is valid
	//return json
	function packagecode_valid(){
		$package_code = $this->input->post('package_code');
		$this->db->select('b.firstname as owner_fname, b.lastname as owner_lname');
		//if code exists
		$this->db->where('a.code',$package_code);
		//if pubished
		$this->db->where('a.status',1);
		//if ramaining qty > 0
		$this->db->where('a.remaining_qty >',0);
		$this->db->limit(1);
		$result = $this->db->get('mlme_product_resell a, mlme_users b');
		$owner_name = '';
		$is_valid = false;
		if($result->num_rows > 0){
			$is_valid = true;
			$code_owner = $result->result();
			$code_owner = $code_owner[0];
			$owner_name = $code_owner->owner_fname.' '.$code_owner->owner_lname;
		}
		echo json_encode( array('is_valid'=>$is_valid, 'owner'=>$owner_name) );
		exit;
	}

	//check if package code is valid
	//return boolean
	function is_packagecode_valid($package_code){
		$this->db->select('resellid');
		//if code exists
		$this->db->where('code',$package_code);
		//if pubished
		$this->db->where('status',1);
		//if ramaining qty > 0
		$this->db->where('remaining_qty >',0);
		$this->db->limit(1);
		$result = $this->db->get('mlme_product_resell');
		$is_valid = false;
		if($result->num_rows > 0){
			$is_valid = true;
		}
		return $is_valid;
	}

}//endclass

